package com.yx.gsyd.controller.sys;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yx.gsyd.comm.DictionaryEnum;
import com.yx.gsyd.entity.SysManager;
import com.yx.gsyd.service.ISysManagerRoleService;
import com.yx.gsyd.service.ISysManagerService;
import com.yx.gsyd.service.ISysRoleMenuService;
import com.yx.gsyd.util.RandomValidateCodeUtil;
import com.yx.gsyd.util.ResultView;
import com.yx.gsyd.util.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Validated
@RestController
@RequestMapping("/api/admin/login")
public class AdminLoginController {

    @Autowired
    private ISysManagerRoleService iHjManagerRoleService;
    @Autowired
    private ISysRoleMenuService iHjRoleMenuService;
    @Autowired
    private ISysManagerService iHjManagerService;

    @PostMapping("/adLogin")
    public ResultView adLogin(@NotNull(message = "账号不能为空") String account,
                              @NotNull(message = "密码不能为空") String pwd,
                              @NotNull(message = "验证码不能为空") String code,
                              HttpServletRequest request){
        //进行登录认证
        QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("m_account",account);
        queryWrapper.eq("is_del", DictionaryEnum.IS_DEL_N.getCode());
        SysManager hjManager=this.iHjManagerService.getOne(queryWrapper);
        if(hjManager==null){
            return ResultView.error("账号不存在！！！");
        }
        if(hjManager.getMStatus()==DictionaryEnum.IS_ENABLE_Y.getCode()){
            return ResultView.error("账号已被禁用！！！");
        }
        if(!RsaUtil.getRsaPwd(hjManager.getMPwd()).equals(pwd)){
            return ResultView.error("密码错误");
        }
        if(request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY)==null){
            return ResultView.error("验证码已过期，请重新获取");
        }
        String sysCode = (String)request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
        if(!sysCode.equalsIgnoreCase(code)) {
            return ResultView.error("验证码填写错误");
        }
        //进行授权注入sa-token权限框架
        StpUtil.login(hjManager.getManagerId());
        //注入用户session-保持session信息共享-保持session底层代码共享
        StpUtil.getSession().set(hjManager.getManagerId(),hjManager);
        return ResultView.ok(StpUtil.getTokenValue());
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
        randomValidateCode.getRandcode(request, response);//输出验证码图片方法
    }

    /**
     * 获取当前用户信息
     */
    @SaCheckLogin
    @GetMapping(value = "/getAccountInfo")
    public ResultView getAccountInfo() {
        Map<String, Object> map = MapUtils.newHashMap();
        String managerId= StpUtil.getLoginIdAsString();
        SysManager sysManager=this.iHjManagerService.getById(managerId);
        map.put("user",sysManager);
        map.put("parentType","");
        if(sysManager.getMType()==6){
            SysManager parent=this.iHjManagerService.getById(sysManager.getParentManagerId());
            map.put("parentType",parent.getMType());
        }
        List<String> permissions = new ArrayList<>();
        List<String> roles =new ArrayList<>();
        if(sysManager.getMAccount().equals("admin")){
            roles.add("admin");
            permissions.add("*:*:*");
            map.put("permissions",permissions);
            map.put("roles",roles);
        }else{
            List<String> menuList=iHjRoleMenuService.getMenuList(managerId);
            for (String menuPerm : menuList) {
                if(!StringUtils.isEmpty(menuPerm)){
                    permissions.add(menuPerm);
                }
            }
            map.put("permissions",permissions);
            List<String> roleList=iHjManagerRoleService.getRoleList(managerId);
            for (String rolePerm : roleList) {
                if(!StringUtils.isEmpty(rolePerm)){
                    roles.add(rolePerm);
                }
            }
            map.put("roles",roles);
        }
        return ResultView.ok(map);
    }

}
